package com.amin.app.web.controller;

import com.alibaba.fastjson.JSON;
import com.amin.app.web.common.config.JwtAuthenticationProvider;
import com.amin.app.web.common.json.Constants;
import com.amin.app.web.common.json.JsonResult;
import com.amin.app.web.entity.*;
import com.amin.app.web.entity.security.JwtLoginToken;
import com.amin.app.web.filter.security.JwtLoginFilter;
import com.amin.app.web.service.*;
import com.amin.app.web.utils.DESUtils;
import com.amin.app.web.utils.JwtUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.*;
import java.util.*;

/**
 * 系统用户控制器
 *
 */
@Controller
public class UserController {
    final
    UserService userService;
    final
    RoleService roleService;
    final
    MenuSerivce menuSerivce;
    final
    RoleMenuService roleMenuService;
    final
    DictListService dictListService;
    final
    DepService depService;
    public UserController(UserService userService, RoleService roleService, MenuSerivce menuSerivce, RoleMenuService roleMenuService, DictListService dictListService, DepService depService) {
        this.userService = userService;
        this.roleService = roleService;
        this.menuSerivce = menuSerivce;
        this.roleMenuService = roleMenuService;
        this.dictListService = dictListService;
        this.depService = depService;
    }

    /**
     * 获取用户列表
     * @param model
     * @return
     */
    @RequestMapping("/user/getUserList")
    public String getUserList(Model model,Page page,SUsers sUsers){
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<SUsers> userList = userService.getUserList(sUsers);
        PageInfo<SUsers> userListPage = new PageInfo<>(userList);
        model.addAttribute("userList",userListPage);
        SRole sRole = new SRole();
        List<SRole> roleList = roleService.getRoleList(sRole);
        model.addAttribute("roleList",roleList);
        SDep sDep = new SDep();
        List<SDep> depList = depService.getDepList(sDep);
        model.addAttribute("depList",depList);
        model.addAttribute("user",sUsers);
        List<SDictList> sys_switch_type = dictListService.getDictListByDictType("sys_switch_type");
        model.addAttribute("systemSwitchType",sys_switch_type);
        List<SDictList> sys_user_type = dictListService.getDictListByDictType("sys_user_type");
        model.addAttribute("systemUserType",sys_user_type);
        return "/amin/user/userList";
    }

    /**
     * 获取用户信息
     * @param model
     * @return
     */
    @RequestMapping("/user/getUserInfo")
    public String getUserInfo(Model model,SUsers sUsers){
        if (null == sUsers.getUserName()){
            SUsers user = userService.getUserById(sUsers.getId());
            SRole sRole = new SRole();
            List<SRole> roleList = roleService.getRoleList(sRole);
            model.addAttribute("roleList",roleList);
            model.addAttribute("user",user);
            SDep sDep = new SDep();
            List<SDep> depList = depService.getDepList(sDep);
            model.addAttribute("depList",depList);
            return "amin/user/userInfo";
        }
        userService.update(sUsers);
        return "redirect:/user/getUserList";
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户登录
     * @param model
     * @return
     */
    @RequestMapping(value = "/login")
    public  Object userLogin(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (null == username){
            return "/login";
        }
        SUsers users = userService.getUserInfoByUserName(username);
        if (null == users) {
            return "/login";
        }
        if (!DESUtils.getEncryptString(password).equals(users.getPassword())){
            model.addAttribute("erroe","密码不正确");
            return "/login";
        }
        List<SMenu> menuList = new ArrayList<>();
        List<RoleMenu> roleMenuList = roleMenuService.getMenuListByRoleId(users.getRoleId());
        for(RoleMenu roleMenu:roleMenuList){
            SMenu menu = menuSerivce.getMenuByIdByMenu(roleMenu.getMenuId());
            if (null != menu){
                menuList.add(menu);
            }
        }
        model.addAttribute("user",users);
        model.addAttribute("menuList",menuList);
        //生成token

        JwtLoginToken jwtLoginToken = new JwtLoginToken(username, password);
        jwtLoginToken.setDetails(new WebAuthenticationDetails(request));
        JwtAuthenticationProvider jwtAuthenticationProvider = new JwtAuthenticationProvider(userService,passwordEncoder);
        Authentication authentication =  jwtAuthenticationProvider.authenticate(jwtLoginToken);
        SUsers jwtUserDetails = (SUsers) authentication.getPrincipal();
        String json = JSON.toJSONString(jwtUserDetails);
        String jwtToken = JwtUtils.createJwtToken(json, Constants.DEFAULT_TOKEN_TIME_MS);
        //签发token
        JsonResult<String> jsonResult = new JsonResult<>();
        jsonResult.setToken(jwtToken);
        jsonResult.setSuccess(jwtToken);
        System.out.println(JSON.toJSONString(jsonResult));
        //response.getWriter().write(JSON.toJSONString(jsonResult));
        model.addAttribute("token",jwtToken);
        return "index";
        //return JSON.toJSONString(jsonResult);
    }

    /**
     * 数据提交
     * @param sUsers
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/dataSubmit")
    public Map<Object,Object> dataSubmit(SUsers sUsers){
        Map<Object,Object> answer = new HashMap<>();
        try {
            if (null == sUsers.getId() || 0 ==  sUsers.getId()){
                System.out.println(sUsers.getId());
                sUsers.setCreatedTime(new Date());
                userService.save(sUsers);
            }else {
                if (null != sUsers.getPassword() && !"".equals(sUsers.getPassword())){
                    sUsers.setPassword(DESUtils.getEncryptString(sUsers.getPassword()));
                }
                userService.update(sUsers);
            }
            answer.put("code",0);
            answer.put("msg","数据保存成功");
        }catch (SqlSessionException e){
            answer.put("code",1);
            answer.put("msg",e.getMessage());
        }
        return answer;
    }

    /**
     * 删除用户
     * @param model
     * @param sUsers
     * @return
     */
    @RequestMapping(value = "/user/delById")
    public String delById(Model model, SUsers sUsers){
        userService.delById(sUsers.getId());
        return "redirect:/user/getUserList";
    }
    /**
     * 创建用户/编辑用户
     * @param model
     * @return
     */
    @RequestMapping(value = "/user/createUser")
    public String createUser(Model model,SUsers sUsers){
        SDep sDep = new SDep();
        List<SDep> depList = depService.getDepList(sDep);
        model.addAttribute("depList",depList);
        SRole sRole = new SRole();
        List<SRole> roleList = roleService.getRoleList(sRole);
        model.addAttribute("roleList",roleList);
        List<SDictList> sys_switch_type = dictListService.getDictListByDictType("sys_switch_type");
        model.addAttribute("systemSwitchType",sys_switch_type);
        List<SDictList> sys_user_type = dictListService.getDictListByDictType("sys_user_type");
        model.addAttribute("systemUserType",sys_user_type);
        sUsers.setSex("1");
        if (null != sUsers.getId() && 0 != sUsers.getId()){
            sUsers = userService.getUserById(sUsers.getId());
        }
        model.addAttribute("user",sUsers);
        return "/amin/user/createUser";
    }
    //@PreAuthorize("hasRole('admin')")
    @RequestMapping("/")
    public String amin(){
        return "/login";
    }

    @PreAuthorize("hasRole('admin')")
    @RequestMapping("/home")
    public String home(){
        return "/home";
    }
    /**
     * 用户注册
     * @param model
     * @param sUsers
     * @return
     */
    @RequestMapping(value = "/registration")
    public String userRegistration(Model model,SUsers sUsers){
        if (null == sUsers.getUserName()){
            return "/registration";
        }
        sUsers.setDepName("暂无");
        sUsers.setPassword(DESUtils.getEncryptString(sUsers.getPassword()));
        sUsers.setCreatedTime(new Date());
        userService.save(sUsers);
        return "login";
    }
    @ResponseBody
    @RequestMapping(value = "/user/updatePicture")
    public Object updatePicture(Model model, @RequestParam("file") MultipartFile file) throws FileNotFoundException {
        Map<String,String> resutlMap = new HashMap<>();
        if(file.isEmpty()){
            resutlMap.put("code","1111");
            resutlMap.put("msg","文件为空");
            return resutlMap;
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);
        String imgPath = "/image/" + fileName;
        String path = "/src/main/resources/static"+imgPath;
        System.out.println(path);
        File dest = new File(System.getProperty("user.dir") + path);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            resutlMap.put("code","0000");
            resutlMap.put("msg","上传成功");
            resutlMap.put("url","http://localhost:8082/amin"+imgPath);
            return resutlMap;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resutlMap.put("code","1111");
            resutlMap.put("msg","文件上传异常");
            return resutlMap;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resutlMap.put("code","1111");
            resutlMap.put("msg","文件上传异常");
            return resutlMap;
        }
       // return "";
    }
}
